<template>
  <div v-if="visible" class="modal-mask" @click.self="close">
    <div class="modal">
      <div class="modal-header">
        <div>新建产品</div>
        <button class="btn" @click="close">关闭</button>
      </div>
      <div class="modal-body">
        <div class="form-row">
          <label>名称</label>
          <div class="field"><input class="input" v-model.trim="form.name" placeholder="请输入名称" /></div>
        </div>
        <div class="form-row">
          <label>版本</label>
          <div class="field"><input class="input" v-model.trim="form.version" placeholder="例如 1.0.0" /></div>
        </div>
        <div class="form-row">
          <label>供应商</label>
          <div class="field"><input class="input" v-model.trim="form.vendor" placeholder="例如 Acme" /></div>
        </div>
        <div class="form-row">
          <label>包管理器</label>
          <div class="field">
            <select class="select" v-model="form.packageManager">
              <option value="">请选择</option>
              <option value="npm">npm</option>
              <option value="yarn">yarn</option>
              <option value="pnpm">pnpm</option>
              <option value="maven">maven</option>
              <option value="gradle">gradle</option>
            </select>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn" @click="close">取消</button>
        <button class="btn primary" :disabled="submitting" @click="onSubmit">{{ submitting ? '提交中...' : '提交' }}</button>
      </div>
    </div>
  </div>
  
</template>

<script>
import { reactive, watch, ref } from 'vue'
import { createProduct } from '../api/products'

export default {
  name: 'CreateProductModal',
  props: {
    visible: { type: Boolean, default: false }
  },
  emits: ['update:visible', 'created'],
  setup(props, { emit }) {
    const form = reactive({ name: '', version: '', vendor: '', packageManager: '' })
    const submitting = ref(false)

    const reset = () => { form.name = ''; form.version = ''; form.vendor = ''; form.packageManager = '' }
    const close = () => emit('update:visible', false)

    watch(() => props.visible, (v) => { if (v) reset() })

    const onSubmit = async () => {
      if (!form.name || !form.version || !form.vendor || !form.packageManager) {
        alert('请完整填写信息')
        return
      }
      submitting.value = true
      try {
        await createProduct({ ...form })
        emit('created')
      } catch (err) {
        alert(err?.message || '创建失败')
      } finally {
        submitting.value = false
      }
    }

    return { form, submitting, close, onSubmit }
  }
}
</script>

